﻿using System;
using System.Reflection;
using Autofac;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using NHibernate.Tool.hbm2ddl;
using PurchaseSales.Manage.Common;
using PurchaseSales.Manage.Common.AOP;
using PurchaseSales.Manage.Model.Entities;
using Configuration = NHibernate.Cfg.Configuration;
using Module = Autofac.Module;

namespace PurchaseSales.Manage
{
    public class NhibernateModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register(c =>
                                 {
                                     var config = new Configuration();
                                     config.SetProperty("show_sql", "true");
                                     config.SetProperty("format_sql", "true");

                                     config.SessionFactory()
                                         .Integrate.Using<MsSql2005Dialect>()
                                         .Connected.By<SqlClientDriver>().ByAppConfing("connectionString");

                                     config.SetInterceptor(new DataBindingIntercepter());
                                     config.AddAssembly(Assembly.Load("PurchaseSales.Manage"));

                                     if (AppConfig.SchemaUpdate)
                                     {
                                         SchemaExport export = new SchemaExport(config);
#if DEBUG
                                         export.Execute(true, true, false);
#else
                                         export.Execute(false, true, false);
#endif
                                         AuthRoles roles = new AuthRoles() { RoleId = Guid.NewGuid(), RoleName = "管理员" };
                                         Users user = new Users() { Name = "admin", AgentId = "admin", Role = roles };

                                         var openSession = config.BuildSessionFactory().OpenSession();
                                         openSession.Save(roles);
                                         openSession.Save(user);
                                         openSession.Flush();
                                     }
                                     return config;

                                 }).As<Configuration>().SingleInstance();

            builder.Register(b => b.Resolve<Configuration>().BuildSessionFactory()).As<ISessionFactory>().SingleInstance();
            builder.Register(b => b.Resolve<ISessionFactory>().OpenSession()).As<ISession>().SingleInstance();

        }

    }
}
